package com.zyp.jobseeker.controller;

import com.github.pagehelper.PageInfo;
import com.zyp.jobseeker.entity.Enterprise;
import com.zyp.jobseeker.enums.UserRole;
import com.zyp.jobseeker.service.EnterpriseService;
import com.zyp.jobseeker.service.UserService;
import com.zyp.jobseeker.utils.JwtUtil;
import com.zyp.jobseeker.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业Controller
 * 处理企业管理相关请求
 */
@RestController
@RequestMapping("/api/enterprise")
public class EnterpriseController {

    @Autowired
    private EnterpriseService enterpriseService;
    private static final Logger logger = LoggerFactory.getLogger(EnterpriseController.class);
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private UserService userService;

    /**
     * 更新企业信息
     */
    @PutMapping("/update")
    @PreAuthorize("hasRole('ENTERPRISE')")
    public ResultUtil<?> updateEnterpriseInfo(@RequestBody Enterprise enterprise) {
        if (enterprise.getId() == null) {
            return ResultUtil.fail(400, "企业ID不能为空");
        }

        if (!enterpriseService.updateEnterpriseInfo(enterprise)) {
            return ResultUtil.fail(500, "企业信息更新失败");
        }
        return ResultUtil.success("企业信息更新成功");
    }

    /**
     * 管理员或学生根据id获取企业信息
     */
    @GetMapping("/info/{id}")
    @PreAuthorize("hasAuthority('ADMIN') or hasAuthority('STUDENT')")  // 管理员/企业权限
    public ResultUtil<?> getEnterpriseInfo(@PathVariable("id") Long userId) {
        Optional<Enterprise> enterprise = enterpriseService.findById(userId);
        return enterprise.map(value -> ResultUtil.success("获取企业信息成功", value))
                .orElseGet(() -> ResultUtil.fail(404, "企业信息不存在"));
    }

    /**
     * 学生/管理员搜索企业
     */
    @GetMapping("/search")
    @PreAuthorize("hasAuthority('STUDENT') or hasAuthority('ADMIN')")  // 学生/管理员权限
    public ResultUtil<PageInfo<Map<String, Object>>> searchEnterprises(
            @RequestHeader("Authorization") String token,  // 获取用户角色
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            // 验证token
            if (token == null || !token.startsWith("Bearer ")) {
                return ResultUtil.fail(401, "未提供有效的认证信息");
            }
            token = token.substring(7);
            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.fail(401, "认证信息已过期，请重新登录");
            }

            String userRole = UserRole.getByCode(jwtUtil.getRoleFromToken(token)).getDesc(); // 获取用户角色
            logger.info("[企业搜索] 收到搜索请求，参数：keyword={}, page={}, size={}, userRole={}",
                    keyword, page, size, userRole);

            PageInfo<Map<String, Object>> result = enterpriseService.searchEnterprises(
                    keyword, page, size, userRole);

            logger.info("[企业搜索] 查询完成，返回结果数: {}", result.getTotal());
            return ResultUtil.success(result);

        } catch (Exception e) {
            logger.error("[企业搜索] 查询失败", e);
            return ResultUtil.fail(500, "企业搜索失败: " + e.getMessage());
        }
    }
}

